<template>
  <div class="detail-container">
    <a-page-header
      title="血糖记录详情"
      :sub-title="`记录ID: ${recordId}`"
      @back="goBack"
    />
    
    <a-row :gutter="24">
      <a-col :span="24">
        <a-card :bordered="false">
          <a-descriptions title="血糖记录信息" bordered :column="{ xxl: 4, xl: 3, lg: 3, md: 2, sm: 1, xs: 1 }">
            <a-descriptions-item label="用户ID">
              {{ recordData.userId }}
            </a-descriptions-item>
            <a-descriptions-item label="用户名">
              {{ recordData.userName }}
            </a-descriptions-item>
            <a-descriptions-item label="昵称">
              {{ recordData.nickname || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="血糖值">
              <span :style="{ color: getValueColor() }">{{ recordData.value }} mmol/L</span>
            </a-descriptions-item>
            <a-descriptions-item label="测量类型">
              {{ recordData.measureTypeText || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="状态">
              <a-tag :color="getStatusTagColor()">
                {{ recordData.statusText || '-' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="测量时间">
              {{ formatDateTime(recordData.measureTime) }}
            </a-descriptions-item>
            <a-descriptions-item label="创建时间">
              {{ formatDateTime(recordData.createTime) }}
            </a-descriptions-item>
            <a-descriptions-item label="备注" :span="3">
              {{ recordData.remark || '无' }}
            </a-descriptions-item>
          </a-descriptions>
          
          <div class="actions">
            <a-popconfirm
              title="确定要删除此记录吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteRecord"
            >
              <a-button type="danger">
                <delete-outlined />
                删除记录
              </a-button>
            </a-popconfirm>
          </div>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="24" style="margin-top: 24px">
      <a-col :span="12">
        <a-card title="用户近期记录" :bordered="false">
          <a-table
            :columns="columns"
            :data-source="recentRecords"
            :pagination="{ pageSize: 5 }"
            :loading="loading"
            row-key="id"
            size="small"
          >
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'value'">
                <span :style="{ color: getRecordValueColor(record) }">{{ text }}</span>
              </template>
              
              <template v-if="column.dataIndex === 'status'">
                <a-tag :color="getRecordStatusColor(record.status)">
                  {{ record.statusText }}
                </a-tag>
              </template>
              
              <template v-if="column.dataIndex === 'measureTime'">
                {{ formatDateTime(text) }}
              </template>
              
              <template v-if="column.dataIndex === 'action'">
                <a @click="viewRecord(record)" v-if="record.id !== recordId">查看</a>
                <span v-else>当前记录</span>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
      
      <a-col :span="12">
        <a-card title="参考范围" :bordered="false">
          <a-alert
            :message="`${recordData.measureTypeText || ''}血糖参考范围`"
            :description="getReferenceRange()"
            :type="getAlertType()"
            show-icon
          />
          
          <a-divider />
          
          <a-alert
            message="血糖建议"
            :description="getAdvice()"
            type="info"
            show-icon
          />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { DeleteOutlined } from '@ant-design/icons-vue';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const recordId = ref(route.params.id);
const recordData = ref({});
const recentRecords = ref([]);
const loading = ref(false);

// 表格列定义
const columns = [
  {
    title: '血糖值',
    dataIndex: 'value',
    width: 100
  },
  {
    title: '测量类型',
    dataIndex: 'measureTypeText',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '测量时间',
    dataIndex: 'measureTime',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 80
  }
];

// 获取记录详情
const fetchRecordDetail = async () => {
  try {
    loading.value = true;
    const response = await axios.get(`/admin/blood-sugar/detail/${recordId.value}`);
    
    if (response.data.code === 0) {
      recordData.value = response.data.data;
      fetchRecentRecords();
    } else {
      message.error(response.data.message || '获取记录详情失败');
    }
  } catch (error) {
    console.error('获取记录详情错误', error);
    message.error('获取记录详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取用户近期记录
const fetchRecentRecords = async () => {
  if (!recordData.value.userId) return;
  
  try {
    loading.value = true;
    
    const response = await axios.get('/admin/blood-sugar/list', { 
      params: {
        userId: recordData.value.userId,
        page: 1,
        size: 10
      }
    });
    
    if (response.data.code === 0) {
      recentRecords.value = response.data.data.records;
    } else {
      message.error(response.data.message || '获取近期记录失败');
    }
  } catch (error) {
    console.error('获取近期记录错误', error);
    message.error('获取近期记录失败');
  } finally {
    loading.value = false;
  }
};

// 删除记录
const deleteRecord = async () => {
  try {
    const response = await axios.delete(`/admin/blood-sugar/${recordId.value}`);
    
    if (response.data.code === 0) {
      message.success('删除成功');
      router.push('/blood-sugar');
    } else {
      message.error(response.data.message || '删除失败');
    }
  } catch (error) {
    console.error('删除记录错误', error);
    message.error('删除失败');
  }
};

// 查看其他记录
const viewRecord = (record) => {
  router.push(`/blood-sugar-detail/${record.id}`);
};

// 获取血糖值状态颜色
const getValueColor = () => {
  if (!recordData.value.statusText) return '';
  
  if (recordData.value.statusText.includes('偏低')) return '#cf1322';
  if (recordData.value.statusText.includes('偏高')) return '#fa8c16';
  return '#52c41a'; // 正常
};

// 获取状态标签颜色
const getStatusTagColor = () => {
  if (!recordData.value.statusText) return '';
  
  if (recordData.value.statusText.includes('偏低')) return 'red';
  if (recordData.value.statusText.includes('偏高')) return 'orange';
  return 'green'; // 正常
};

// 获取记录的值颜色
const getRecordValueColor = (record) => {
  if (!record.statusText) return '';
  
  if (record.statusText.includes('偏低')) return '#cf1322';
  if (record.statusText.includes('偏高')) return '#fa8c16';
  return '#52c41a'; // 正常
};

// 获取记录的状态颜色
const getRecordStatusColor = (status) => {
  if (!status) return '';
  
  if (status === 2) return 'red'; // 偏低
  if (status === 3) return 'orange'; // 偏高
  return 'green'; // 正常
};

// 获取参考范围提示类型
const getAlertType = () => {
  if (!recordData.value.status) return 'info';
  
  switch (recordData.value.status) {
    case 1: return 'success'; // 正常
    case 2: return 'warning'; // 偏低
    case 3: return 'error'; // 偏高
    default: return 'info';
  }
};

// 获取参考范围文本
const getReferenceRange = () => {
  // 根据测量类型返回参考范围
  const measureType = recordData.value.measureType;
  
  if (!measureType) return '无参考数据';
  
  switch (measureType) {
    case 1: // 空腹
      return '空腹血糖正常范围: 3.9-6.1 mmol/L';
    case 2: // 餐后2小时
      return '餐后2小时血糖正常范围: <7.8 mmol/L';
    case 3: // 随机
      return '随机血糖正常范围: 3.9-7.8 mmol/L';
    default:
      return '无参考数据';
  }
};

// 获取建议文本
const getAdvice = () => {
  if (!recordData.value.status) return '暂无建议';
  
  switch (recordData.value.status) {
    case 1: // 正常
      return '您的血糖值在正常范围内，请继续保持良好的生活习惯。';
    case 2: // 偏低
      return '您的血糖值偏低，请注意补充碳水化合物，避免低血糖。如有头晕、心悸等不适症状，请及时就医。';
    case 3: // 偏高
      return '您的血糖值偏高，请控制饮食，多运动，按时服用降糖药物。如有口渴、多尿等不适症状，请及时就医。';
    default:
      return '暂无建议';
  }
};

// 格式化日期时间
const formatDateTime = (dateTimeArr) => {
  if (!dateTimeArr || !Array.isArray(dateTimeArr) || dateTimeArr.length < 5) return '-';
  
  // 日期数组格式: [年, 月, 日, 时, 分]
  const [year, month, day, hour, minute] = dateTimeArr;
  const formattedMonth = String(month).padStart(2, '0');
  const formattedDay = String(day).padStart(2, '0');
  const formattedHour = String(hour).padStart(2, '0');
  const formattedMinute = String(minute).padStart(2, '0');
  
  return `${year}-${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}`;
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  fetchRecordDetail();
});
</script>

<style scoped>
.detail-container {
  padding: 24px;
}

.actions {
  margin-top: 24px;
  text-align: right;
}
</style> 